package cn.kgc.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author 课工场
 * @date 2024/8/21
 * @description
 */
public class CustomerRealm extends AuthorizingRealm {

    // 授权方法 当用户访问受限资源时  该方法会被自动调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);
        //  TODO  根据用户信息查询 用户具有的权限信息   角色  权限字符串

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        // simpleAuthorizationInfo.addRole("super");
        simpleAuthorizationInfo.addStringPermission("sys:user:select");
        simpleAuthorizationInfo.addStringPermission("sys:user:delete");

        return simpleAuthorizationInfo;
    }


    // 认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken  = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        if ("root".equals(username)){
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("root", "47f3bebaa5baf1b61124697c5f1a786a",
                    ByteSource.Util.bytes("java2425"), this.getName());

            return simpleAuthenticationInfo;
        }


        return null;
    }
}
